import {Component, OnInit, ViewChild} from '@angular/core';
import {FormBuilder, FormControl, FormGroup} from "@angular/forms";
import {FileUploadComponent} from "../../../shared/component/file-upload/file-upload.component";
import {ActivatedRoute, ParamMap, Router} from "@angular/router";
import {CamManageService} from "../../../shared/service/cam-manage.service";
import {Vehicle} from "../../../shared/model/vehicle";
import {Driver} from "../../../shared/model/driver";
import {CamType} from "../../../shared/model/camType";
import {DriverTableComponent} from "../../../shared/component/driver-table/driver-table.component";
import {FileUploader} from "ng2-file-upload";
import MTSConstants from "../../../shared/config/config";
import {Attach} from "../../../shared/model/attach";
import {Http, RequestOptions} from "@angular/http";
import {SingleOpenWinService} from "../../../shared/service/single-open-win.service";
declare var $:any;

@Component({
  selector: 'app-cam-manage-edit',
  templateUrl: './cam-manage-edit.component.html',
  styleUrls: ['./cam-manage-edit.component.css']
})
export class CamManageEditComponent implements OnInit {

  file: Array<Object>;
  vehicleForm:FormGroup;
  vehicle:Vehicle;
  driver:Driver;
  userId:string = this.routeInfo.snapshot.queryParams ["userId"];
  gasolineTypes:any=[{
    "id":0,
    "name":"90#汽油"
  },{
    "id":1,
    "name":"92#汽油"
  },{
    "id":2,
    "name":"95#汽油"
  },{
    "id":3,
    "name":"97#汽油"
  },{
    "id":4,
    "name":"5＃柴油"
  },{
    "id":5,
    "name":"0＃柴油"
  },{
    "id":6,
    "name":"－10＃柴油"
  },{
    "id":7,
    "name":"－20＃柴油"
  },{
    "id":8,
    "name":"－35＃柴油"
  },{
    "id":9,
    "name":"－50＃柴油"
  }];
  radioValue:number;
  vehicleTypes:CamType[];
  vehicletype:CamType;
  @ViewChild(FileUploadComponent) child :FileUploadComponent;
  @ViewChild(DriverTableComponent) driverTable:DriverTableComponent;

  imguploader: FileUploader = new FileUploader({
    url: `${MTSConstants.HOSTUser}attach/upload`,
    method: "POST",
    autoUpload: false,
    // maxFileSize: 100
  });
  imgMsg: string = "";
  imgList: Attach[] = [];
  imgoid: string[] = [];
  imgoids: string = "";

  constructor(
    private fb:FormBuilder,
    private router:Router,
    private routeInfo:ActivatedRoute,
    private camManageService:CamManageService,
    private http:Http,
    private singleOpenWinService:SingleOpenWinService
  ) { }

  ngOnInit() {
    //初始化购买日期
    $('#purchaseDate').datetimepicker({
      format: 'YYYY-MM-DD',
      locale: 'zh-cn',
      minDate:new Date(),
      ignoreReadonly: true
    });

    //初始化年检时间
    $('#annualCheckDate').datetimepicker({
      format: 'YYYY-MM-DD',
      locale: 'zh-cn',
      minDate:new Date(),
      ignoreReadonly: true
    });

    this.createForm();

    this.camManageService.getVehicleTypes().then(res=>{
      this.vehicleTypes = res;
    });

    this.routeInfo.paramMap
      .switchMap((params: ParamMap) => this.camManageService.getVehicleByOID(this.routeInfo.snapshot.params["oid"]))
      .subscribe(vehicle => {
        this.singleOpenWinService.oidChange.emit(this.routeInfo.snapshot.params["oid"]);

        this.imgList = [];
        this.imgoid = [];
        this.imgoids = "";

        this.vehicle = vehicle.vehicle;
        this.driver = vehicle.driver;
        this.vehicletype = vehicle.vehicle;
        //获取所有附件
        let attachments = vehicle.attachments;
        if(attachments){
          for(let i=0;i<attachments.length;i++){
            //判断附件类型 infoType=1则为车辆图片
            if(attachments[i].infoType === 1){
              this.imgList.push(attachments[i]);
            }
          }
        }
        //展示车辆图片使其可以点击下载
        for(var i=0;i<this.imgList.length;i++){
          this.imgList[i].filePath = `${MTSConstants.HOSTUser}attach/download/${this.imgList[i].oid}`;
          this.imgoid.push(this.imgList[i].oid);
        }
        if(!this.driver){
          this.vehicleForm.reset({
            oid:this.vehicle.oid,
            name:this.vehicle.name,
            vehicleType:this.vehicle.vehicleType,
            licenseNumber:this.vehicle.licenseNumber,
            gasolineType:this.vehicle.gasolineType,
            displacement:this.vehicle.displacement,
            averageConsumption:this.vehicle.averageConsumption,
            vehicleValue:this.vehicle.vehicleValue,
            purchaseDateToString:this.vehicle.purchaseDate,
            carport:this.vehicle.carport,
            annualCheckDateToString:this.vehicle.annualCheckDate,
            engineModel:this.vehicle.engineModel,
            passengerCapacity:this.vehicle.passengerCapacity,
            loadCapacity:this.vehicle.loadCapacity,
            etc:this.vehicle.etc,
            image:this.vehicle.image,
            vehicleStatus:this.vehicle.vehicleStatus,
            description:this.vehicle.description
          });
        }else{
          this.vehicleForm.reset({
            oid:this.vehicle.oid,
            name:this.vehicle.name,
            vehicleType:this.vehicle.vehicleType,
            licenseNumber:this.vehicle.licenseNumber,
            gasolineType:this.vehicle.gasolineType,
            displacement:this.vehicle.displacement,
            averageConsumption:this.vehicle.averageConsumption,
            driver:this.driver.oid,
            driverName:this.driver.name,
            driverPhone:this.driver.phone,
            vehicleValue:this.vehicle.vehicleValue,
            purchaseDateToString:this.vehicle.purchaseDate,
            carport:this.vehicle.carport,
            annualCheckDateToString:this.vehicle.annualCheckDate,
            engineModel:this.vehicle.engineModel,
            passengerCapacity:this.vehicle.passengerCapacity,
            loadCapacity:this.vehicle.loadCapacity,
            etc:this.vehicle.etc,
            image:this.vehicle.image,
            vehicleStatus:this.vehicle.vehicleStatus,
            description:this.vehicle.description
          });
        }


        this.radioValue = this.vehicle.etc;
        let date = $('#purchaseTime').val();
        $('#purchaseTime').val(date.split(" ")[0]);
        date = $('#annualCheckTime').val();
        $('#annualCheckTime').val(date.split(" ")[0]);
        $('#vehicleType').val(this.vehicle.vehicleType);
        $('#licenseNumber').val(this.vehicle.licenseNumber);
      });

    //订阅司机开窗
    this.singleOpenWinService.driverChange.subscribe((info:string)=>{
      $('#driver').val(this.driverTable.selected.oid);
      $('#driverName').val(this.driverTable.selected.name);
      $('#driverPhone').val(this.driverTable.selected.phone);
      this.driverIsVisible = false;
    });

  }

  //初始化Form
  createForm(){
    this.vehicleForm =this.fb.group({
      oid:'',
      name:'',
      vehicleType:'',
      licenseNumber:'',
      gasolineType:'',
      displacement:'',
      averageConsumption:'',
      driver:'',
      driverName: new FormControl({value: '', disabled: true}),
      driverPhone: new FormControl({value: '', disabled: true}),
      vehicleValue:'',
      purchaseDateToString:'',
      carport:'',
      annualCheckDateToString:'',
      engineModel:'',
      passengerCapacity:'',
      loadCapacity:'',
      etc:'',
      image:'',
      vehicleStatus:'',
      description:''
    });
  }

  //表单提交
  onSubmit(val:any){
    if(this.checkData()){
      if($('#purchaseTime').val()){
        this.vehicleForm.patchValue({
          purchaseDateToString: $('#purchaseTime').val()
        });
      }
      if($('#annualCheckTime').val()){
        this.vehicleForm.patchValue({
          annualCheckDateToString: $('#annualCheckTime').val()
        });
      }
      if($('#driverName').val()){
        this.vehicleForm.patchValue({
          driver:$('#driver').val(),
          driverName:$('#driverName').val(),
          driverPhone:$('#driverPhone').val()
        });
      }
      this.camManageService.updateVehicle(this.vehicleForm.value,this.child.fileoids,this.imgoids).then(res=>{
        if(res.code ===1){
          alert(res.message);
          this.camManageService.listFreshEvent.emit("edit");
          this.camManageService.searchFreshEvent.emit("edit");
          this.singleOpenWinService.oidChange.emit("new");
          this.router.navigateByUrl('camManage/new');
        }else{
          alert(res.message);
        }
      })
    }
  }

  //数据卡控
  checkData(){
    let msg ="";
    let reg = /^(0|[1-9][0-9]*)+(.[0-9]{1,2})?$/;	//判断只能为数字
    let regexp=/^[1-9]\d*$/;   //判断只能为整数
    if(!$("#name").val().replace(/^\s+|\s+$/g,"")){
      msg +=("请输入车辆名称！\n");
    }
    if(!$("#licenseNumber").val().replace(/^\s+|\s+$/g,"")){
      msg +=("请输入车牌号！\n");
    }
    if($("#displacement").val().replace(/^\s+|\s+$/g,"") && !reg.test($("#displacement").val())){
      msg +=("排量请填写数字，且小数点后只能保存两位！\n");
    }
    if($("#averageConsumption").val().replace(/^\s+|\s+$/g,"") && !reg.test($("#averageConsumption").val())){
      msg +=("平均油耗请填写数字，且小数点后只能保存两位！\n");
    }
    if($("#vehicleValue").val().replace(/^\s+|\s+$/g,"") && !reg.test($("#vehicleValue").val())){
      msg +=("购买价格请填写数字，且小数点后只能保存两位！\n");
    }
    if($("#passengerCapacity").val().replace(/^\s+|\s+$/g,"") && !regexp.test($("#passengerCapacity").val())){
      msg +=("额定载客数请填写整数！\n");
    }
    if($("#loadCapacity").val().replace(/^\s+|\s+$/g,"") && !reg.test($("#loadCapacity").val())){
      msg +=("额定载重量请填写数字，且小数点后只能保存两位！\n");
    }
    if(msg){
      alert(msg);
      return false;
    }else{
      return true;
    }
  }

  /**
   * 单选司机开窗
   * @type {boolean}
   */
  driverIsVisible = false;

  driverShowModal = () => {
    this.driverIsVisible = true;
  }

  driverHandleCancel = (e) => {
    this.driverIsVisible = false;
  }

  //选择司机
  btn_select_onclick(){
    this.driverTable.ngOnInit();
    this.driverShowModal();
  }

  //选中文件后上传
  selectedImgOnChanged(event: any) {
    //文件上传
    // let files = event.target.files;
    //检查文件大小
    let checkMsg = this.checkImg();
    if(checkMsg!=""){
      alert(checkMsg);
    }

    //上传所有文件
    this.imguploader.uploadAll();
    //文件上传成功时调用
    this.imguploader.onSuccessItem = (item, res, status, headers) => {
      //上传多个文件会执行多次
      if (status == 200) {
        this.delImg();
        this.imgList =[];
        this.imgoid = [];
        this.imgoids = "";
        // 上传文件成功后获取服务器返回的数据
        let file = new Attach();
        let xx = JSON.parse(res);
        // file.filesize = xx[0].filesize;
        // file.name = xx[0].name;
        file.oid = xx[0].oid;
        file.infoType = xx[0].infoType;
        if(file.infoType === 2 || !file.infoType){
          file.filePath = `${MTSConstants.HOSTUser}attach/download/${xx[0].oid}`;
          this.imgoid.push(file.oid);
          this.imgoids = this.imgoid.join(";");
          this.imgList.push(file);
        }
      }
    };

    //文件上传失败时调用
    this.imguploader.onErrorItem = (item, res, status, headers) => {
      this.imgMsg += item.file.name+' 上传失败\n';
    }

    //文件上传操作全部执行完成后调用
    this.imguploader.onCompleteAll = () => {
      if(!this.imgMsg){
        alert('图片上传成功');
      }else{
        alert(this.imgMsg);
        this.imgMsg = "";
      }
    }
  }

  //检查文件大小及类型
  checkImg():string{
    let msg = "";
    for(var i=0; i<this.imguploader.queue.length; i++){
      // console.log(this.imguploader.queue[i].file.size)
      if(this.imguploader.queue[i].file.size>`${MTSConstants.imgSize}`){
        msg+=this.imguploader.queue[i].file.name+"图片大小超过限制！\n";
        this.imguploader.queue[i].remove();
        i--;
      }
      let imgName = this.imguploader.queue[i].file.name;
      let ext = imgName.substr(imgName.lastIndexOf(".")).toLowerCase();//获得图片后缀名
      if(`${MTSConstants.imgType}`.indexOf(ext.split(".")[1])===-1){
        msg+=this.imguploader.queue[i].file.name+"图片类型不匹配！\n";
        this.imguploader.queue[i].remove();
        i--;
      }
    }
    return msg;
  }

  delImgClick(){
    if(confirm("删除后不可恢复，确认删除吗？")){
      this.delImg();
    }
  }

  delImg(){
    if(this.imgList.length>0){
      let oid = this.imgList[0].oid;
      const url = `${MTSConstants.HOSTUser}attach/invalid/${oid}`;
      const headers = MTSConstants.headers;//spring的restful接口用这个
      const options = new RequestOptions({ headers: headers });
      this.http.post(url, options)
        .toPromise();
      this.imgList = [];
    }
  }

}
